using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CodeWork.DAL.BDHomePage;
using System.Collections.Generic;
using CodeWork.Library.Data;
using CodeWork.Library.Web;
using System.Data.SqlTypes;
using CodeWork.Library;

public partial class admin_BannedList : BasePage
{
	private SecurityLevel _securityLevel = SecurityLevel.One;
	
    public string GrvBannedListSortOrder
    {
        get
        {
            string orderBy = " id ";

            if (ViewState["orderBy"] != null)
                orderBy = ViewState["orderBy"].ToString();
            else
                ViewState["orderBy"] = orderBy;

            return orderBy;
        }
        set { ViewState["orderBy"] = value; }
    }

    public int GrvBannedListStartRow
    {
        get
        {
            int startRow = 0;

            if (ViewState["startRow"] != null)
                int.TryParse(ViewState["startRow"].ToString(), out startRow);
            else
                ViewState["startRow"] = startRow;

            return startRow;
        }
        set { ViewState["startRow"] = value; }
    }

    private int _totalItems;

    public int TotalItems
    {
        get 
        { 
            Banned banned = new Banned();
            this._totalItems = banned.LoadCount(PrepareFilterConditions());
            return this._totalItems; 
        }
        set { this._totalItems = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptInclude("ApplicationCommon", "../javascripts/ApplicationCommon.js");

        if (!IsPostBack)
        {
            try
            {
                BindGrid();
            }
            catch (Exception ex)
            {
                LoadMessage = CommonMessage.CommonErrorMessage;
            }
        }
    }

    private List<Condition> PrepareFilterConditions()
    {
        List<Condition> conditions = new List<Condition>();

        string bannedIp = Security.BindStringInput(tbxBannedIp.Text, _securityLevel);
		conditions.Add(new Condition("banned_ip", ConditionOperator.Like, bannedIp, JoinOperator.FirstValue));

        return conditions;
    }

    private void BindGrid()
    { 
        Banned banned = new Banned();
        List<Condition> conditions = PrepareFilterConditions();

        string orderBy = GrvBannedListSortOrder;
        int startRow = GrvBannedListStartRow;
        int pageSize = grvBannedList.PageSize;

        List<Banned> banneds = banned.Load(orderBy, startRow, pageSize, conditions);

		if (banneds.Count == 0)
        {
            GrvBannedListStartRow -= grvBannedList.PageSize;
            if (GrvBannedListStartRow < 0)
                GrvBannedListStartRow = 0;

            banneds = banned.Load(orderBy, GrvBannedListStartRow, pageSize, conditions);
        }

        grvBannedList.DataSource = banneds;
        grvBannedList.DataBind();
        
        BindPager();
        
        string start = (GrvBannedListStartRow + 1).ToString();
        string end = ((GrvBannedListStartRow + grvBannedList.PageSize) > TotalItems ? TotalItems.ToString() : (GrvBannedListStartRow + grvBannedList.PageSize).ToString());
        if (TotalItems == 0)
            start = "0";
        pagerLabel.Text = "Showing " + start + " to " + end + " of " + TotalItems.ToString();
    }
    
    private void BindPager()
    {
        pager.DataSource = Utility.PreparePagingData(TotalItems, grvBannedList.PageSize);
        pager.DataBind();
    }

    protected void grvBannedList_RowCommand(object sender, CommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "editCommand")
                Response.Redirect("bannededit.aspx?id=" + e.CommandArgument.ToString());
            else if (e.CommandName == "deleteCommand")
            {
                Banned.Delete(Convert.ToInt32(e.CommandArgument));
                BindGrid();
            }
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void grvBannedList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox selectAll = (CheckBox)e.Row.FindControl("selectAll");
                selectAll.Attributes.Add("onclick", "SelectAll('" + grvBannedList.ClientID + "','" + selectAll.ClientID + "')");
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Int32 id = (Int32)grvBannedList.DataKeys[e.Row.RowIndex].Value;

                ImageButton editButton = (ImageButton)e.Row.FindControl("editButton");
                editButton.CommandArgument = id.ToString();
                editButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/row_edit.gif";

                ImageButton deleteButton = (ImageButton)e.Row.FindControl("deleteButton");
                deleteButton.CommandArgument = id.ToString();
                deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete?');");
                deleteButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/row_delete.gif";
            }
        }
        catch(Exception ex)
        {
            LoadMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void AddNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("bannededit.aspx");
    }

    protected void Delete_Selected(object sender, EventArgs e)
    {
        try
        {
            GridViewRowCollection grvBannedListRows = grvBannedList.Rows;
            List<int> idToDelete = new List<int>();

            foreach (GridViewRow row in grvBannedListRows)
            {
                CheckBox rowSelection = (CheckBox)row.FindControl("rowSelect");

                if (rowSelection.Checked)
                    idToDelete.Add((int)grvBannedList.DataKeys[row.RowIndex].Value);
            }

            if (Banned.Delete(idToDelete))
                BindGrid();
            else
                ResponseMessage = CommonMessage.DeleteErrorMessage;
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void Filter_Click(object sender, EventArgs e)
    {
        try
        {
            BindGrid();
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void grvBannedList_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(GrvBannedListSortOrder))
            {
                if (GrvBannedListSortOrder == e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Ascending))
                    GrvBannedListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Descending);
                else if (GrvBannedListSortOrder == e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Descending))
                    GrvBannedListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(SortDirection.Ascending);
                else
                    GrvBannedListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(e.SortDirection);
            }
            else
                GrvBannedListSortOrder = e.SortExpression + " " + Utility.ConvertSortDirectionToSql(e.SortDirection);

            BindGrid();
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void Pager_Command(object sender, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "first" || e.CommandName == "last" || e.CommandName == "paging")
            {
                GrvBannedListStartRow = Convert.ToInt32(e.CommandArgument) * grvBannedList.PageSize;
            }
            else if (e.CommandName == "prev")
            {
                GrvBannedListStartRow -= grvBannedList.PageSize;
                if (GrvBannedListStartRow < 0)
                    GrvBannedListStartRow = 0;
            }
            else if (e.CommandName == "next")
            {
                GrvBannedListStartRow += grvBannedList.PageSize;
                if (GrvBannedListStartRow > ((TotalItems-1) / grvBannedList.PageSize) * grvBannedList.PageSize)
                    GrvBannedListStartRow = ((TotalItems-1) / grvBannedList.PageSize) * grvBannedList.PageSize;
            }
            
            BindGrid();
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }

    protected void Pager_DataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                ImageButton firstButton = (ImageButton)e.Item.FindControl("btnFirst");
                firstButton.CommandArgument = "0";
                firstButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/first-page.png";
                ImageButton prevButton = (ImageButton)e.Item.FindControl("btnPrev");
                prevButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/prev-page.png";
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                ImageButton lastButton = (ImageButton)e.Item.FindControl("btnLast");
                lastButton.CommandArgument = ((TotalItems-1) / grvBannedList.PageSize).ToString();
                lastButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/last-page.png";
                ImageButton nextButton = (ImageButton)e.Item.FindControl("btnNext");
                nextButton.ImageUrl = "~/App_Themes/" + Page.StyleSheetTheme + "/images/next-page.png";
            }
        }
        catch (Exception ex)
        {
            ResponseMessage = CommonMessage.CommonErrorMessage;
        }
    }
}
